<template>
  <div class="insurance w100 h100">
    <div class="search-bar">
      <el-input placeholder="请输入场所名称/营业执照/身份证/保单编号进行搜索" v-model="searchText" clearable @clear="getWarranty">
        <template slot="append">
          <div class="search-btn" @click="handleSearch">搜索</div>
        </template>
      </el-input>
    </div>
    <div class="poeple-list" >
      <div class='add-user'>
        <!--<el-button  type='primary' icon='el-icon-plus' @click="handleAddWarranty">新增保单</el-button>-->
        <el-button  type='primary' icon='el-icon-download' @click="handleExportBatch"  v-has-permission="'warranty_export'">批量导出</el-button>
      </div>
      <el-table :data='listData' stripe class='reg-tab' :header-cell-style="setHeaderStyle" :row-style="setCellRowStyle"
                v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50">
        </el-table-column>
        <el-table-column :prop="item.prop"  :width="item.prop === 'idNumber' ? '180' : 'auto'" :label="item.label" v-for="(item, index) in tableHead" :key="index"
                         :formatter="item.prop === 'insuredType' ? insuredTypeFormatter : null"></el-table-column>
        <el-table-column label='承保详情'>
          <template slot-scope='scope'>
            <el-button type='text' size='small' @click="handleView(scope.row)" title="查看">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label='操作'>
          <template slot-scope='scope'>
            <el-button type='text' size='small' @click="handleExportOne(scope.row)" title="导出" v-has-permission="'warranty_export'">
              <img src='../../../../static/image/main/download.png' alt=''></el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" title="删除" v-has-permission="'warranty_delete'">
              <img src="../../../../static/image/common/delete.png" alt>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <div class='page-left'>
          <span>共{{ this.total}}条数据 </span>
          <span>每页:</span>
          <el-input placeholder="条数" v-model="inputs" @blur="pagesizeChange" @keyup.enter.native="pagesizeChange" clearable> </el-input>
          <span>条</span>
        </div>
        <el-pagination background layout="prev, pager, next, jumper"
                       :page-size="pageSize" :total="total"
                       @current-change="handleCurrentChanges" id='page' :current-page.sync="currentPage">
        </el-pagination>
      </div>
    </div>
    <!--查看保单承保详情-->
    <el-dialog title="承保详情" :visible.sync="deviceDialogVisible" :close-on-press-escape="false"
               :close-on-click-modal="false" width="700px" class="center">
      <div class="device-list">
        <el-table :data='devices' stripe class='reg-tab' :header-cell-style="setHeaderStyle" :row-style="setCellRowStyle" v-loading="loading">
          <el-table-column :prop="item.prop" :label="item.label" v-for="(item, index) in deviceTableHead" :key="index"></el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <!--新增保单承保详情-->
    <!--<el-dialog title="新增保单" :visible.sync="warrantyDialogVisible" :close-on-press-escape="false"-->
               <!--:close-on-click-modal="false" width="422px" class="center">-->
      <!--<el-form :model="warrantyForm" :rules="warrantyRules" ref="warrantyForm" label-width="110px" class="demo-form">-->
        <!--<el-form-item label="场所名称" prop="placeName">-->
          <!--<el-input v-model="warrantyForm.placeName"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="被投保人类型" prop="industry">-->
          <!--<el-select v-model="warrantyForm.industry" placeholder="请选择被投保人类型" class="w100">-->
            <!--<el-option :label="item.label" :value="item.prop" v-for="(item, index) in insuredType" :key="index"></el-option>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="行业" prop="insuredType" v-if="warrantyForm.industry === 2">-->
          <!--<el-select v-model="warrantyForm.insuredType" placeholder="请选择行业" class="w100">-->
            <!--<el-option :label="item.label" :value="item.prop" v-for="(item, index) in industryData" :key="index"></el-option>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="身份证号" prop="idNumber" v-if="warrantyForm.industry === 1">-->
          <!--<el-input v-model="warrantyForm.idNumber" maxlength="18" minlength="18"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="营业证号" prop="idNumber" v-if="warrantyForm.industry === 2">-->
          <!--<el-input v-model.number="warrantyForm.idNumber" maxlength="18" minlength="18"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="投保设备" prop="imeiList">-->
          <!--<el-input v-model="warrantyForm.imeiList"></el-input>-->
        <!--</el-form-item>-->
      <!--</el-form>-->
      <!--<div slot="footer" class="dialog-footer">-->
        <!--<el-button @click="cancelAddWarranty" class="cancel-btn">取  消</el-button>-->
        <!--<el-button type="primary" @click="addWarranty('warrantyForm')">确  定</el-button>-->
      <!--</div>-->
    <!--</el-dialog>-->
    <!--按照时间段导出保单-->
    <el-dialog title="批量导出" :visible.sync="exportDialogVisible" :close-on-press-escape="false"
               :close-on-click-modal="false" width="456px" class="center">
      <div class="device-list">
        <el-form :model="exportForm" ref="ruleForm" label-width="100px">
          <el-form-item label="开始时间：">
            <el-form-item prop="startTime">
              <el-date-picker prefix-icon="" placeholder="选择日期" v-model="exportForm.startTime"
                              @change="handleStartChange" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-form-item>
          <el-form-item label="结束时间：">
            <el-form-item prop="endTime">
              <el-date-picker prefix-icon="" placeholder="选择日期" v-model="exportForm.endTime"
                              @change="handleEndChange" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-form-item>
        </el-form>
        <div class="days">
          <div class="day" :class="days === item.prop ? 'selected' : ''" v-for="(item, index) in dayArr" :key="index"
               @click="handleDayClick(item)">{{item.label}}</div>
        </div>
        <div class="btns">
          <el-button @click="exportDialogVisible = false" class="cancel-btn function-btn">取  消</el-button>
          <el-button type="primary" class="function-btn" @click.stop="sure">确  定</el-button>
        </div>
      </div>
    </el-dialog>
    <!--删除弹出框-->
    <delete-dialog :is-show="deleteDialogShow" :desc="deleteDesc" @close="handleClose"></delete-dialog>
  </div>
</template>

<script>
  import Config from '../../../config'
  import DeleteDialog from "../../../components/CommonDialog";
  export default {
    name: 'Insurance',
    components: {
      DeleteDialog
    },
    data () {
      return {
        // 搜索
        searchText: '',
        tableHead: [
          {prop: 'index', label: '序号'},
          // {prop: 'placeName', label: '场所名称'},
          // {prop: 'industry', label: '行业'},
          {prop: 'insuranceId', label: '保单编号'},
          {prop: 'insuredType', label: '被投保人类型'},
          {prop: 'idNumber', label: '营业执照/身份证号'},
          {prop: 'createTime', label: '投保日期'},
          {prop: 'effectiveTime', label: '生效日期 '},
          {prop: 'expireTime', label: '到期日期'}
        ],
        // 表格数据
        listData: [],
        // 分页
        total: 1,
        currentPage: 1,
        pageSize: 15,
        inputs:15,
        // loading
        loading: false,
        // 行业，投保人类型Map
        industryMap: null,
        insuredTypeMap: null,
        // 被保设备弹框
        deviceDialogVisible: false,
        devices: [],
        deviceTableHead: [
          {prop: 'index', label: '序号'},
          {prop: 'imei', label: '设备编号'},
          {prop: 'cus_site_name', label: '场所名称'},
          {prop: 'cus_site_type', label: '场所类型'},
        ],
        // 新增保单
        warrantyDialogVisible: false,
        warrantyForm: {
          imeiList: '',
          insuredType: '',
          idNumber: '',
          industry: '',
          placeName: '',
          userId: ''
        },
        warrantyRules: {
          insuredType: [{required: true, message: '请选择省份', trigger: 'change'}],
          industry: [{required: true, message: '请选择城市', trigger: 'change'}],
          idNumber: [{required: true, message: '请填写安装地址', trigger: 'blur'}],
          placeName: [{required: true, message: '请填写安装位置', trigger: 'blur'}],
          imeiList: [{required: true, message: '请填写设备编号', trigger: 'blur'}],
        },
        industryData: [
          {prop: 1, label: '普通'},
          {prop: 2, label: '仓储'},
          {prop: 3, label: '易燃、易爆'},
        ],
        insuredType: [
          {prop: 1, label: '个人'},
          {prop: 2, label: '商户'},
        ],
        // 导出保单弹框
        exportDialogVisible: false,
        warrantyBatch: [],
        exportForm: {
          startTime: undefined,
          endTime: undefined,
        },
        days: 0,
        dayArr: [
          {prop: 7, label: '近一周'},
          {prop: 30, label: '近一月'},
          {prop: 90, label: '近三月'},
          {prop: 180, label: '近半年'},
          {prop: 365, label: '近一年'},
        ],
        // 删除保单
        deleteDialogShow: false,
        deleteDesc: '',
        deleteObject: null,
      }
    },
    mounted () {
      this.initTypeMap()
      this.getWarranty()
    },
    methods: {
      /**
       * 初始化类型Map对象
       * */
      initTypeMap () {
        this.industryMap = new Map()
        this.industryMap.set('1', '普通')
        this.industryMap.set('2', '仓储')
        this.industryMap.set('3', '易燃、易爆')
        this.insuredTypeMap = new Map()
        this.insuredTypeMap.set('1', '个人')
        this.insuredTypeMap.set('2', '商户')
      },
      /**
       * 当前页变化
       * */
      handleCurrentChanges(val) {
        this.currentPage = val
        this.getWarranty();
      },
      /**
       * 每页大小变化
       * */
      pagesizeChange () {
        if (+this.inputs === 0) {
          this.inputs = 15
        }
        if (Number.isInteger(+this.inputs)) {
          this.pageSize = +this.inputs
          this.getWarranty()
        } else {
          this.$message({
            message: '请输入整数',
            type: 'warning'
          })
        }
      },
      handleSearch () {
        // 搜索的时候从第一页开始搜
        this.currentPage = 1
        this.getWarranty()
      },
      /**
       * 从后台获取保单列表
       * */
      getWarranty () {
        this.loading = true
        const url = `${Config.SCM_WEIXIN_ADMIN_URL}/insurance/getByPageList`
        let param = {
          offset: this.currentPage - 1,
          pagesize: this.pageSize
        }
        if (this.searchText) {
          param.insuranceId = this.searchText
        }
        // TODO 判断是否需要添加搜索条件
        this.$http.get(url, param)
          .then(data => {
            this.loading = false
            const list = data.pageList
            this.listData.splice(0)
            list.forEach((item, index) => {
              if (this.currentPage === 1) {
                item.index = index + 1;
              } else {
                item.index = (this.currentPage - 1) * this.pageSize + index + 1;
              }
              this.listData.push(item)
            })
            this.total = data.totalCount
          })
          .catch(e => {
            this.$message({
              message: '获取保单列表失败',
              type: 'warning'
            })
            this.loading = false
          })
      },
      /**
       * 表头添加背景颜色
       * */
      setHeaderStyle ({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return 'background: #f9f9f9; color: #333; font-size: 12px; height: 39px;'
        }
      },
      setCellRowStyle ({ row, column, rowIndex, columnIndex }) {
        if (rowIndex % 2 === 0) {
          return 'background: #fff; color: #666; font-size: 12px; height: 39px;'
        } else {
          return 'background: #f9f9f9; color: #666; font-size: 12px; height: 39px;'
        }
      },
      /**
       * 表格格式化行业类型
       * */
      industryFormatter (row, column) {
        return this.industryMap.get(row.industry) || ''
      },
      /**
       * 表格格式化投保人类型
       * */
      insuredTypeFormatter (row, column) {
        return this.insuredTypeMap.get(row.insuredType)
      },
      /**
       * 多选框处理事件
       * */
      handleSelectionChange(val) {
        this.warrantyBatch = val
      },
      handleAddWarranty () {
        this.warrantyDialogVisible = true
      },
      cancelAddWarranty () {
        this.warrantyDialogVisible = false
      },
      addWarranty (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.save()
          } else {
            this.$message(
              {
                message: '格式不正确',
                type: 'warning'
              }
            )
            return false
          }
        })
      },
      /**
       * 批量导出
       * */
      async handleExportBatch () {
        if (this.warrantyBatch.length > 0) { // 用户有勾选，不按照时间导出
          const policyNos = this.warrantyBatch
          const params = this.getParams({policyNos})
          this.createExport(params)
          return
        }
        this.exportDialogVisible = true
      },
      handleStartChange () {
        this.days = 0
        if (!this.exportForm.startTime) {
          return
        }
        const now = new Date().getTime()
        if (this.exportForm.endTime) {
          if (this.exportForm.startTime.getTime() > this.exportForm.endTime.getTime()) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'warning'
            })
            this.exportForm.startTime = null
          }
        }
        if (this.exportForm.startTime && this.exportForm.startTime.getTime() > now) {
          this.$message({
            message: '开始时间不能大于当天',
            type: 'warning'
          })
          this.exportForm.startTime = null
        }
        console.log(this.exportForm)
      },
      handleEndChange () {
        this.days = 0
        if (!this.exportForm.endTime) {
          return
        }
        if (this.exportForm.startTime) {
          if (this.exportForm.startTime.getTime() > this.exportForm.endTime.getTime()) {
            this.$message({
              message: '结束时间不能小于开始时间',
              type: 'warning'
            })
            this.exportForm.startTime = null
          }
        }
        console.log(this.exportForm)
      },
      handleDayClick (item) {
        this.days = item.prop
        this.exportForm = {
          startTime: undefined,
          endTime: undefined,
        }
      },
      sure () {
        // 判断用户输入是否正确
        if (this.days === 0 && !this.exportForm.startTime && !this.exportForm.endTime) {
          this.$message({
            message: '请选择时间段进行查询',
            type: 'warning'
          })
          return
        }

        if (this.days === 0) { // 按照起始时间查询
          if (!this.exportForm.startTime) {
            this.$message({
              message: '请选择开始时间',
              type: 'warning'
            })
            return
          }
          if (!this.exportForm.endTime) {
            this.$message({
              message: '请选择结束时间',
              type: 'warning'
            })
            return
          }
          const startTime = this.getTimeString(this.exportForm.startTime)
          const endTime = this.getTimeString(this.exportForm.endTime)
          const params = this.getParams({startTime, endTime})
          this.createExport(params)
        } else {
          const days = this.days
          const params = this.getParams({days})
          this.createExport(params)
        }
        this.exportDialogVisible = false
      },
      /**
       * 获取时间字符串 '2019-01-01'
       * @param date {Date}
       * @return String
       * */
      getTimeString (date) {
        const util = this.$util.Date
        return `${util.getYear(date)}-${util.getMonth(date)}-${util.getDate(date)}`
      },
      /**
       *  导出一个保单
       * */
      handleExportOne (row) {
        console.log(row)
        const policyNos = [row]
        const params = this.getParams({policyNos})
        const title = `保单-${row.insuranceId}`
        this.createExport(params, title)
      },
      async createExport (params, title) {
        const warranty = await this.getExportData(params)
        if (!warranty) {
          this.$message({
            message: '查询保单信息失败',
            type: 'warning'
          })
          return
        }
        if (warranty.length === 0) {
          this.$message({
            message: '没有查询到保单信息',
            type: 'warning'
          })
          return
        }
        const exportData = this.createXlsxJsonData(warranty)
        const filename = title || this.getXlsxName(params)
        this.export2Xlsx(exportData, filename)
      },
      getXlsxName (params) {
        let title = '保单-'
        if (params.days !== 0) {
          title += `${this.getLabelByProp(params.days)}`
        } else if (params.startTime && params.endTime) {
          title += `${params.startTime}至${params.endTime}`
        } else {
          title += `批量`
        }
        return title
      },
      getLabelByProp (prop) {
        let str = ''
        this.dayArr.some(item => {
          if (item.prop === prop) {
            str = item.label
            return true
          }
        })
        return str
      },
      /**
       * 构造查询参数
       * */
      getParams (params) {
        const defaultParams = {
          days: 0,
          policyNos: [],
          startTime: '',
          endTime: ''
        }
        if (params.policyNos) {
          params.policyNos = params.policyNos.map(item => item.id)
        }
        return {...defaultParams, ...params}
      },
      getExportData (params) {
        return new Promise((resolve, reject) => {
          const url = `${Config.SCM_WEIXIN_ADMIN_URL}/insurance/exportInsurance`
          this.$http.post(url, params)
            .then(data => {
              if (data && data.length > 0) {
                resolve(data)
                return
              }
              resolve(null)
            })
            .catch(() => resolve(null))
        })
      },
      /**
       * 构造xlsx用json导出excel的json
       * */
      createXlsxJsonData (arr) {
        const temp = []
        // 处理excel标题
        const key = []
        this.tableHead.forEach(item => {
          key.push(item.label)
        })
        key.push('承保设备')
        key.push('安装地点')
        key.push('场所名称')
        key.push('场所类型')
        temp.push(key)
        console.log(key)
        // 处理excel内容
        arr.forEach((item, index) => {
          temp.push([index + 1, item.insuranceId, this.insuredTypeFormatter(item), item.idNumber, item.createTime, item.effectiveTime, item.expireTime,
            item.imei, item.equipSiteAddress, item.cusSiteName, item.cusSiteType])
        })
        console.log(temp)
        return temp
      },
      /**
       * 批量导出
       * */
      export2Xlsx (data, name = '保单') {
        /* original data */
        var filename = `${name}.xlsx`;
        // var data = [[1,2,3],[true, false, null, "sheetjs"],["foo","bar",new Date("2014-02-19T14:30Z"), "0.3"], ["baz", null, "qux"]]
        var ws_name = "SheetJS";

        if(typeof console !== 'undefined') console.log(new Date());
        var wb = XLSX.utils.book_new(), ws = XLSX.utils.aoa_to_sheet(data);

        /* add worksheet to workbook */
        XLSX.utils.book_append_sheet(wb, ws, ws_name);

        /* write workbook */
        if(typeof console !== 'undefined') console.log(new Date());
        XLSX.writeFile(wb, filename);
        if(typeof console !== 'undefined') console.log(new Date());
      },
      isExpire (row) {
        const expireTime = row.expireTime && new Date(row.expireTime).getTime()
        const now = new Date().getTime()
        return row.state === '0' || now > expireTime
      },
      /**
       * 承保详情预览
       * */
      async handleView (row) {
        console.log(row)
        if (this.isExpire(row)) {
          this.$message({
            message: '该保单已失效',
            type: 'warning'
          })
          return
        }
        const devices = await this.getDevicesByWarrantyId(row.id)
        if (devices.length === 0) {
          this.deviceDialogVisible = false
          this.$message({
            message: '暂无承保详情',
            type: 'warning'
          })
        } else {
          devices.forEach((item, index) => {
            item.index = index + 1
          })
          this.devices = devices
          this.deviceDialogVisible = true
        }
      },
      getDevicesByWarrantyId (id) {
        return new Promise((resolve, reject) => {
          const url = `${Config.DEVICE_MANAGE_URL}/inventory/queryCommon?policy_no=${id}`
          this.$http.get(url)
            .then(data => {
              if (data && data.array) {
                resolve(data.array)
                return
              }
              resolve([])
            })
            .catch(() => resolve([]))
        })
      },
      handleDelete (row) {
        console.log(row)
        this.deleteObject = row
        this.deleteDialogShow = true
        this.deleteDesc = `确定要删除${row.insuranceId}吗？`
      },
      handleClose (boolean) {
        this.deleteDialogShow = false;
        if (!boolean) {
          this.deleteObject = null;
          return;
        }
        const url = `${Config.SCM_WEIXIN_ADMIN_URL}/insurance/delete`
        const params = {id: this.deleteObject.id}
        this.$http.post(url, params)
          .then(data => {
            this.deleteObject = null;
            this.$message.success("删除成功");
            this.getWarranty();
          })
          .catch(e => {
            this.deleteObject = null;
            this.$message.success("删除失败");
          });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .insurance {
    .search-bar {
      width: 580px;
      & /deep/ .el-input--suffix .el-input__inner {
        height: 42px;
        line-height: 42px;
        box-sizing: border-box;
      }
      & /deep/ .el-input-group__append, .el-input-group__prepend {
        padding: 0;
        width: 80px;
        background-color: #EB3838;
        &:hover {
          background-color: #e03131;
        }
      }
      .search-btn {
        width: 100%;
        text-align: center;
        margin-right: 0;
        line-height: 28px;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
      }
    }
    .poeple-list {
      width: 100%;
      height: calc(100% - 62px);
      background: $white;
      margin-top: 20px;
      .add-user {
        height: 24px;
        line-height: 24px;
        margin-right: 27px;
        text-align: right;
        padding-top: 16px;
      }
      .pagination{
        padding: 32px 0 44px 23px;
        .page-left{
          font-size: 12px;
          display: inline-block;
          .el-input--suffix{
            width: 56px;
          }
        }
      }
    }
    .center /deep/ .el-dialog {
      padding-bottom: 32px;
    }
    .device-list {
      & /deep/ .el-table {
        padding: 0 !important;
      }
      .device {
        width: 280px;
        height: 50px;
        background: rgba(255,255,255,1);
        box-shadow: 0px 3px 7px 0px rgba(204, 204, 204, 0.35);
        font-size: 18px;
        color: #EB3838;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      & /deep/ .el-input--prefix .el-input__inner {
        padding-left: 30px;
      }
      .days {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 24px 0 40px;
        .day {
          width: 72px;
          height: 32px;
          line-height: 32px;
          text-align: center;
          box-sizing: border-box;
          border: 1px solid #D9D9D9;
          color: #333;
          font-size: 12px;
          border-radius: 4px;
          cursor: pointer;
        }
        .selected {
          background-color: #eb3838;
          color: #fff;
        }
      }
      .btns {
        text-align: center;
      }
    }
    .dialog-footer {
      height: 28px;
      text-align: center;
      margin: 60px 0 0 0;
      .el-button {
        padding: 7px 27px;
        height: 28px;
        width: 86px;
      }
    }
  }
</style>
